package com.ruoyi.system.service.impl;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

@Service
public class TokenServiceTest {
    //@Todo 先把时间写死，写成一个月


//    @Value("${app.token.expiration-seconds}")
//    private int tokenExpirationSeconds;
    private int tokenExpirationSeconds = 60 * 60 * 24 * 30;

    private final StringRedisTemplate redisTemplate;

    public TokenServiceTest(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public String generateToken(String userDataJson) {
        String token = Base64.getEncoder().encodeToString(userDataJson.getBytes(StandardCharsets.UTF_8));
        storeToken(token, userDataJson);
        return token;
    }

    private void storeToken(String token, String userDataJson) {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        token="user:token:"+token;
        ops.set(token, userDataJson, tokenExpirationSeconds, TimeUnit.SECONDS);
    }

    public String getUserDataFromToken(String token) {
        String userDataJson = redisTemplate.opsForValue().get(token);
        if (userDataJson != null) {
            redisTemplate.expire(token, tokenExpirationSeconds, TimeUnit.SECONDS);
        }
        return userDataJson;
    }
}